<template>
  <div class="chat-window">
    <div class="chat-header">
      <el-avatar :size="40" :src="chat.avatar" />
      <div class="header-info">
        <div class="chat-status">
          <el-tag v-if="chat.status == 'online'" size="small" type="success">在线</el-tag>
          <el-tag v-else size="small" type="info">离线</el-tag>
        </div>
        <div class="chat-title">{{ chat.remark || chat.nickname }}</div>
      </div>
    </div>

    <el-scrollbar ref="scrollbar" class="message-list" @scroll="handleScroll">
      <div class="message-container">
        <!-- 加载更多指示器 -->
        <div v-if="isLoading" class="loading-more">
          <el-icon class="is-loading">
            <Loading />
          </el-icon>
          加载中...
        </div>
        <message-item v-for="message in chat.messages" :key="message.id" :message="message"
          :is-last-message="message.id == chat.messages[chat.messages.length - 1]?.id" :friendAvatar="chat.avatar" />
      </div>
    </el-scrollbar>

    <div class="input-area">
      <div class="toolbar">
        <el-button type="text" @click="toggleEmojiPicker">
          <el-icon :size="20">
            <Sunny />
          </el-icon>
        </el-button>
        <el-button type="text" @click="triggerFileInput('image')">
          <el-icon :size="20">
            <Picture />
          </el-icon>
        </el-button>
        <el-button type="text" @click="triggerFileInput('file')">
          <el-icon :size="20">
            <Folder />
          </el-icon>
        </el-button>
        <el-button type="text" @click="toggleRecording">
          <el-icon :size="20">
            <Microphone />
          </el-icon>
        </el-button>
        <div class="call-buttons">
          <el-button type="primary" size="small" @click="startVoiceCall">
            <el-icon>
              <Microphone />
            </el-icon> 语音通话
          </el-button>
          <el-button type="primary" size="small" @click="startVideoCall">
            <el-icon>
              <VideoCamera />
            </el-icon> 视频通话
          </el-button>
        </div>
        <input ref="fileInput" type="file" style="display: none" @change="handleFileUpload"
          accept="image/*, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx">
      </div>

      <emoji-picker v-if="showEmojiPicker" @select-emoji="insertEmoji" @close="showEmojiPicker = false" />

      <div v-if="isRecording" class="recording-indicator">
        <el-icon class="recording-icon">
          <Mic />
        </el-icon>
        <span>正在录音... {{ recordingTime }}s</span>
        <el-button type="danger" size="small" @click="stopRecording">停止</el-button>
      </div>

      <el-input v-model="inputMessage" type="textarea" :rows="3" placeholder="输入消息..."
        @keyup.enter.exact="sendTextMessage" />

      <div class="action-bar">
        <el-button type="primary" @click="sendTextMessage">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import {
  Picture, Folder, VideoCamera, Microphone, Sunny, Mic
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import MessageItem from '@/components/MessageItem.vue'
import EmojiPicker from '@/components/EmojiPicker.vue'
import { getChatHistory } from '@/api/message'
import { useUserStore } from "@/stores/user";
import { uploadFile } from '@/api/file'

const props = defineProps({
  chat: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['send-message', 'start-call'])

// 状态
const inputMessage = ref('')
const scrollbar = ref(null)
const fileInput = ref(null)
const showEmojiPicker = ref(false)
const isRecording = ref(false)
const recordingTime = ref(0)
let recordingInterval = null
let mediaRecorder = null
let audioChunks = []
const isLoading = ref(false);
const hasMore = ref(true);

const userStore = useUserStore();

// 方法
const scrollToBottom = () => {
  nextTick(() => {
    if (scrollbar.value) {
      scrollbar.value.setScrollTop(scrollbar.value.wrapRef.scrollHeight)
    }
  })
}

const sendTextMessage = () => {
  if (inputMessage.value.trim()) {
    emit('send-message', {
      type: 'text',
      content: inputMessage.value
    })
    inputMessage.value = ''
    scrollToBottom()
  }
}

const toggleEmojiPicker = () => {
  showEmojiPicker.value = !showEmojiPicker.value
}

const insertEmoji = (emoji) => {
  inputMessage.value += emoji
  showEmojiPicker.value = false
}

const triggerFileInput = (type) => {
  if (type == 'image') {
    fileInput.value.accept = 'image/*'
  } else {
    fileInput.value.accept = '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx'
  }
  fileInput.value.click()
}

const handleFileUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 添加文件大小限制
  const MAX_IMAGE_SIZE = 1 * 1024 * 1024; // 1MB
  const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB

  if (file.type.startsWith('image/') && file.size > MAX_IMAGE_SIZE) {
    ElMessage.error('图片不能超过1MB')
    event.target.value = ''
    return
  } else if (!file.type.startsWith('image/') && file.size > MAX_FILE_SIZE) {
    ElMessage.error('文件不能超过10MB')
    event.target.value = ''
    return
  }

  const formData = new FormData()
  formData.append('file', file)

  try {
    const res = await uploadFile(formData)
    if (file.type.startsWith('image/')) {
      emit('send-message', {
        type: 'image',
        content: res.url,
        fileName: file.name
      })
    } else {
      emit('send-message', {
        type: 'file',
        content: res.url,
        fileName: file.name,
        fileSize: file.size
      })
    }
  } catch (err) {
    console.error('上传失败:', err)
    ElMessage.error('文件上传失败')
  } finally {
    event.target.value = ''
  }
}

const toggleRecording = async () => {
  if (isRecording.value) {
    stopRecording()
    return
  }

  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    mediaRecorder = new MediaRecorder(stream, {
      mimeType: 'audio/webm;codecs=opus'
    })
    audioChunks = []

    mediaRecorder.ondataavailable = (event) => {
      audioChunks.push(event.data)
    }

    mediaRecorder.onstop = async () => {
      const audioBlob = new Blob(audioChunks, { type: 'audio/webm' })
      const formData = new FormData()
      const file = new File([audioBlob], `recording-${Date.now()}.webm`, { type: 'audio/webm' })
      formData.append('file', file)

      try {
        const res = await uploadFile(formData)
        emit('send-message', {
          type: 'audio',
          content: res.url, // 确保从服务器返回 URL
          duration: recordingTime.value
        })
      } catch (err) {
        console.error('上传失败:', err)
      }

      stream.getTracks().forEach(track => track.stop())
    }

    mediaRecorder.start()
    isRecording.value = true
    recordingTime.value = 0
    recordingInterval = setInterval(() => {
      recordingTime.value++
    }, 1000)
  } catch (error) {
    console.error('录音失败:', error)
  }
}

const stopRecording = () => {
  if (mediaRecorder && isRecording.value) {
    mediaRecorder.stop()
    clearInterval(recordingInterval)
    isRecording.value = false
  }
}

const startVoiceCall = () => {
  emit('start-call', 'voice')
}

const startVideoCall = () => {
  emit('start-call', 'video')
}

// 监听滚动事件，实现滚动加载更多
const handleScroll = ({ scrollTop }) => {
  if (scrollTop === 0 && !isLoading.value && hasMore.value) {
    loadMoreMessages();
  }
};

// 加载更多消息
const loadMoreMessages = async () => {
  if (!props.chat?.id || isLoading.value) return;

  isLoading.value = true;
  try {
    const userId = userStore.userInfo?.id;
    const currentPage = Math.ceil(props.chat.messages.length / 20) + 1;
    const res = await getChatHistory({ formId: userId, toId: props.chat.id, pageNum: currentPage, pageSize: 20 });


    if (res && res && res.length > 0) {
      // 确保API返回的数据是按时间降序排列的
      const sortedMessages = res.sort((a, b) => new Date(a.createTime) - new Date(b.createTime));
      // 使用 Set 去重已有消息
      const existingIds = new Set(props.chat.messages.map(m => m.id));
      const uniqueMessages = res
        .map(msg => ({
          ...msg,
          id: `msg-${msg.id}`,
          isMe: msg.fromId == userId,
          time: new Date(msg.createTime),
          status: 'sent'
        }))
        .filter(msg => !existingIds.has(msg.id));

      // 插入到聊天记录头部
      props.chat.messages = [...uniqueMessages, ...props.chat.messages];

      // 保持滚动位置
      nextTick(() => {
        if (scrollbar.value?.wrapRef) {
          const newScrollHeight = scrollbar.value.wrapRef.scrollHeight;
          const scrollDiff = newScrollHeight - scrollbar.value.wrapRef.clientHeight;
          scrollbar.value.setScrollTop(scrollDiff);
        }
      });
    } else {
      hasMore.value = false;
    }
  } catch (error) {
    console.error("加载更多消息失败:", error);
  } finally {
    isLoading.value = false;
  }
};

// 添加滚动监听
onMounted(() => {
  if (scrollbar.value?.wrapRef) {
    scrollbar.value.wrapRef.addEventListener('scroll', handleScroll);
  }
});
</script>

<style scoped>
.chat-window {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid #e6e6e6;
}

.header-info {
  display: flex;
  margin-left: 10px;
  flex: 1;
}

.chat-title {
  margin-left: 10px;
  margin-top: 2px;
}

.call-buttons {
  margin-left: auto;
  display: flex;
  gap: 10px;
  align-items: center;
}

.message-list {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.message-container {
  display: flex;
  flex-direction: column;
}

.input-area {
  border-top: 1px solid #e6e6e6;
  padding: 10px;
  position: relative;
}

.toolbar {
  display: flex;
  gap: 5px;
  margin-bottom: 10px;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.recording-indicator {
  display: flex;
  align-items: center;
  padding: 8px;
  background-color: #fef0f0;
  border-radius: 4px;
  margin-bottom: 10px;
}

.recording-icon {
  color: #f56c6c;
  margin-right: 10px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0.5;
  }

  100% {
    opacity: 1;
  }
}

.loading-more {
  text-align: center;
  padding: 10px;
  color: #999;
  font-size: 12px;
}

.is-loading {
  animation: rotating 2s linear infinite;
  margin-right: 5px;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>